﻿@typeparam TValue
@inherits ValidateBase<bool?>

<Checkbox TValue="bool?"
          @ref="cbo"
          DisplayText="@DisplayText"
          ShowLabel="false"
          ShowAfterLabel="true"
          IsDisabled="IsDisabled"
          State="(Value.HasValue?(Value.Value?CheckboxState.Checked:CheckboxState.UnChecked):CheckboxState.Indeterminate)"
          class="me-2"
          OnStateChanged="@OnStateChangedAsync" />

@code
{
    public Checkbox<bool?>? cbo{get;set;}

    [Parameter]
    public CheckboxState State { get; set; } = CheckboxState.Indeterminate;


    [Parameter]
    public EventCallback<CheckboxState> StateChanged{ get; set; }

    public bool? PreviousValue { get; set; } = null;

    async Task OnStateChangedAsync(CheckboxState state, bool? value)
    {
        switch (state)
        {
            case CheckboxState.UnChecked:
                await ValueChanged.InvokeAsync(false);
                break;
            case CheckboxState.Checked:
                await ValueChanged.InvokeAsync(true);
                break;
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
        {
            if (Value.HasValue)
            {
                if (Value.Value == true && PreviousValue == false)
                {
                    await ValueChanged.InvokeAsync(null);
                }
            }
            PreviousValue = Value;

        }
    }
}